import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:mtf/app/routes/app_pages.dart';
import 'package:mtf/app/utils/cache/AppCahche.dart';
import 'package:webview_flutter/webview_flutter.dart';

class AppUtils {
  static void loginCheck(Function onTap) {
    if (AppCache.isLogin()) {
      onTap();
    } else {
      Get.toNamed(Routes.LOGIN);
    }
  }

  static void authCheck(Function onTap) {
    print('authCheck${AppCache.getUserInfo().authStatus}');
    if (AppCache.isLogin()) {
      if (AppCache.getUserInfo().authStatus == 2) {
        onTap();
      } else {
        showPopConfirm("请先实名认证。","取消","去认证",(){
          Get.toNamed(Routes.AUTHENTICATION);
        });
      }
    } else {
      Get.toNamed(Routes.LOGIN);
    }
  }

  static void authAndMt5Check(Function onTap) {
    if (AppCache.isLogin()) {
      if (AppCache.getUserInfo().authStatus == 2) {
        if(AppCache.getUserInfo().mt5Login!=null){
          onTap();
        }else{
          showPopConfirm("请前往充值界面激活mt5账号。","取消","去充值",(){
            Get.toNamed(Routes.RECHARGE);
          });
        }
      } else {
        showPopConfirm("请先实名认证。","取消","去认证",(){
          Get.toNamed(Routes.AUTHENTICATION);
        });
      }
    } else {
      Get.toNamed(Routes.LOGIN);
    }
  }

  static void showPopConfirm(
      String message, String cancelLabel, String okLabel, Function onTap) {
    showOkCancelAlertDialog(
            context: Get.context!!,
            title: '提示',
            message: message,
            cancelLabel: cancelLabel,
            okLabel: okLabel,
            useActionSheetForIOS: true,
            defaultType: OkCancelAlertDefaultType.cancel)
        .then((value) {
      if (value.index == 0) {
        onTap();
      }
    });
  }

  static String dateToString(DateTime? dateTime) {
    if(dateTime!=null){
      var dateFormat=DateFormat("yyyy-MM-dd HH:mm");
      return dateFormat.format(dateTime);
    }else{
      return "";
    }

  }

  static Future<int> getHtmlHeight(WebViewController webViewController) async {
    const javascriptCode = '''
      (function(){
        var doc = document;
        if (!doc || !doc.documentElement){
          return -1;
        } else{
          return Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight);
        }
      })();
    ''';

    try {
      final result =await webViewController.runJavaScriptReturningResult(javascriptCode);
      print('result---${result}');
      int height = int.parse(result.toString());
      return height;
    } catch (_) {
      print("Failed to evaluate JavaScript code.");
      return -1;
    }
  }
}
